<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div v-if="resultCode === 1" class="loading-wrap">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div v-if="resultCode === 2" class="article-detail">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <!-- 关注组件 -->
          <!-- <follow-user 
            :author-id="article.aut_id"
            :is-followed="article.is_followed"
            @updateFollow="article.is_followed=$event"
          /> -->
          <!-- <follow-user 
            :author-id="article.aut_id"
            :value="article.is_followed"
            @input="article.is_followed=$event"
          /> -->
          <!-- 一个组件只有一个v-model -->
          <follow-user
            :author-id="article.aut_id"
            v-model="article.is_followed"
          />
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content markdown-body"
          ref="content"
          v-html="article.content"
        ></div>
        <van-divider>正文结束</van-divider>

        <!-- 评论组件 -->
        <comment-list
          :list="commentList"
          @click-reply="onClickReply"
          @updateTotalCommentNum="totalCommentNum = $event"
          :source-id="article.art_id"
        />
        <!-- 评论弹框组件 -->
        <van-popup
          v-model="isCommentPostShow"
          position="bottom"
          :style="{ height: '18%' }"
        >
          <comment-post
          @updateCommentList="onUpdateCommentList"
           :target-id="article.art_id"/>
        </van-popup>
        <!-- 评论回复弹窗组件 -->
        <van-popup
          v-model="isReplyShow"
          position="bottom"
          :style="{ height: '100%' }"
        >
        <comment-reply
        v-if="isReplyShow"
        @click-close="isReplyShow=false"
        :comment="currentComment"
        :article-id="article.art_id"
        ></comment-reply>
        </van-popup>
        <!-- /评论回复弹窗组件 -->
        <!-- /评论弹框组件 -->

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="isCommentPostShow = true"
            >写评论</van-button
          >
          <van-icon name="comment-o" :badge="totalCommentNum" color="#777" />
          <!-- 收藏组件 -->
          <!-- <article-collect :value='article.is_collected'  @input="article.is_collected=$event" ></article-collect> -->
          <article-collect
            :article-id="article.art_id"
            v-model="article.is_collected"
          ></article-collect>

          <!-- 点赞组件 -->
          <article-like
            :article-id="article.art_id"
            v-model="article.attitude"
          ></article-like>
          <van-icon name="share" color="#777777"></van-icon>
        </div>
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div v-if="resultCode === 3" class="error-wrap">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div v-if="resultCode === 4" @click="loadArticle" class="error-wrap">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn">点击重试</van-button>
      </div>
      <!-- /加载失败：其它sh未知错误（例如网络原因或服务端异常） -->
    </div>
  </div>
</template>

<script>
import { getArticleById } from "@/api/article";
import { ImagePreview } from "vant";
import FollowUser from "@/components/follow-user";
import ArticleCollect from "@/components/article-collect";
import ArticleLike from "@/components/article-like";
import CommentList from "./components/comment-list";
import CommentPost from "./components/comment-post";
import CommentReply from "./components/comment-reply";
export default {
  name: "ArticleIndex",
  components: {
    FollowUser,
    ArticleCollect,
    ArticleLike,
    CommentList,
    CommentPost,
    CommentReply
  },
  props: {
    // 定义props去接收动态路由的数据信息。
    // 可以直接通过 this.articleId 读取动态路由数据
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      resultCode: 1, // 1表示加载中，2表示成功，3表示资源不存在，4表示错误
      article: {}, // 文章数据信息
      totalCommentNum: "", // 评论总数
      isCommentPostShow: false, // 评论弹框显示
      commentList:[], // 评论列表
      isReplyShow: false, // 评论恢复弹出显示
      currentComment:{} // 评论信息
    };
  },
  created() {
    this.loadArticle();
  },
  methods: {
    // 请求文章数据
    async loadArticle() {
      this.resultCode = 1;
      try {
        // 测试代码
        // if(Math.random()>.5){
        //   console.log(JSON.parse('absdsdf'))
        // }
        // 发送请求
        const { data: res } = await getArticleById(this.articleId);
        // 赋值数据
        this.article = res.data;
        // 成功获取数据
        this.resultCode = 2;
        // 给所有图片绑定预览事件（等到DOM渲染完成之后再做）
        this.bindImgClick();
      } catch (error) {
        if (error.response.status === 404) {
          // 资源不存在
          this.resultCode = 3;
        } else {
          // 获取出错
          this.resultCode = 4;
        }
        console.log(error);
      }
    },
    // 绑定图片预览功能
    bindImgClick() {
      this.$nextTick(() => {
        // 1.找到所有文章正文里面的图片节点
        let imgNodes = this.$refs.content.getElementsByTagName("img");
        imgNodes = Array.from(imgNodes); // 节点集合变成数组
        // 2.取出所有图片地址
        let imgUrls = imgNodes.map(val => val.src);
        // 3.每个图片节点绑定事件
        imgNodes.forEach((img, idx) => {
          img.onclick = function() {
            // 4.调用图片预览器
            ImagePreview({
              images: imgUrls,
              startPosition: idx
            });
          };
        });
      });
    },
    // 添加数据
    onUpdateCommentList(val){
      this.commentList.unshift(val)
      this.isCommentPostShow = false
    },
    onClickReply(val){
      this.currentComment = val
      this.isReplyShow = true
    }
  }
};
</script>

<style scoped lang="less">
@import url("./github-markdown.css");
.article-container {
  .main-wrap {
    z-index: 2000;
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    /deep/ .van-button--plain {
      border: none;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
